import React from 'react';
import { Form, Space, Button } from 'antd';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import Resizer from './Resizer';
import {
  getBoxStyle,
  getLayoutStyle,
  getTailStyle,
  getFormItemStyle,
  getItemCountsPerRow,
  getRowCountsInExpanded,
  isCollapseSwitchVisible,
  getTailRowIndex,
} from './utils';

function Querier (props) {
  console.log(props, '222');

  const { form: extForm, items = [], onQuery = () => { } } = props;

  const [form] = Form.useForm(extForm);
  const [collapsed, setCollapsed] = React.useState(true);
  const [boxWidth, setBoxWidth] = React.useState(undefined);

  const itemCountsPerRow = getItemCountsPerRow(boxWidth);
  const rowCountsInExpanded = getRowCountsInExpanded(items.length, itemCountsPerRow);

  const collapseSwitchVisible = isCollapseSwitchVisible(rowCountsInExpanded);
  const tailRowIndex = getTailRowIndex(collapsed, collapseSwitchVisible, rowCountsInExpanded);

  const triggerOnQuery = () => {
    const fieldsValue = form.getFieldsValue();
    console.log('fieldsValue', fieldsValue);
    onQuery(fieldsValue);
  };

  const renderItems = () => {
    return items.map((item, index) => {
      const { style, ...restProps } = item;

      return (
        <div key={item.name ?? index}>
          <Form.Item style={{ ...getFormItemStyle(), ...style }} {...restProps} />
        </div>
      );
    });
  };

  const renderTail = () => {
    return (
      <Space>
        <Button type="primary" onClick={triggerOnQuery}>
          查询
        </Button>
        <Button
          onClick={() => {
            form.resetFields();
            triggerOnQuery();
          }}
        >
          重置
        </Button>
        {collapseSwitchVisible && (
          <Button
            type="link"
            onClick={() => {
              setCollapsed(!collapsed);
            }}
          >
            {collapsed ? '展开' : '收起'}
            {collapsed ? <DownOutlined /> : <UpOutlined />}
          </Button>
        )}
      </Space>
    );
  };

  return (
    <div style={getBoxStyle(collapsed)}>
      <Resizer
        onResize={({ scrollWidth }) => {
          setBoxWidth(scrollWidth);
        }}
      >
        <Form autoComplete="off" noValidate form={form}>
          <div style={getLayoutStyle()}>
            {renderItems()}
            <div style={getTailStyle(tailRowIndex)}>{renderTail()}</div>
          </div>
        </Form>
      </Resizer>
    </div>
  );
}

export default Querier;
